package com.atguigu.hotitems_analysis.analysis;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Properties;

/**
 * @author zkq
 * @date 2022/10/2 14:55
 */
public class KafkaProducerUtil {
    public static void main(String[] args) throws Exception {
        writeToKafka("hotitems");
    }
    //包装一个写入kafka的方法
    public static void writeToKafka(String topic) throws Exception{
        Properties properties = new Properties();
        properties.setProperty("bootstrap.servers","hadoop102:9092");
        properties.setProperty("key.serializer",
                "org.apache.kafka.common.serialization.StringSerializer");
        properties.setProperty("value.serializer",
                "org.apache.kafka.common.serialization.StringSerializer");
        //定义一个kafkaProducer
        KafkaProducer<String, String> producer = new KafkaProducer<>(properties);
        //用缓冲流读取文本文件
        BufferedReader bufferedReader = new BufferedReader(new FileReader("F:\\javasecode220620\\UserBehaviorAnalysis\\HotItemsAnalysis\\src\\main\\resources\\UserBehavior.csv"));
        String line;
        while ((line = bufferedReader.readLine())!= null){
            ProducerRecord<String, String> record = new ProducerRecord<>(topic, line);
            producer.send(record);
        }
        producer.close();
    }
}
